<!--
 * @Author: your name
 * @Date: 2022-03-13 09:51:09
 * @LastEditTime: 2022-03-13 10:28:33
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \算法测试\day0906\393.编码验证.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /**
 * @param {number[]} data
 * @return {boolean}
 */
        const MASK1 = 1 << 7;
        const MASK2 = (1 << 7) + (1 << 6);

        var validUtf8 = function (data) {
            const m = data.length;
            let index = 0;
            while (index < m) {
                const num = data[index];
                const n = getBytes(num);
                if (n < 0 || index + n > m) {
                    return false;
                }
                for (let i = 1; i < n; i++) {
                    if (!isValid(data[index + i])) {
                        return false;
                    }
                }
                index += n;
            }
            return true;
        };

        const getBytes = (num) => {
            if ((num & MASK1) === 0) {
                return 1;
            }
            let n = 0;
            let mask = MASK1;
            while ((num & mask) !== 0) {
                n++;
                if (n > 4) {
                    return -1;
                }
                mask >>= 1;
            }
            return n >= 2 ? n : -1;
        }

        const isValid = (num) => {
            return (num & MASK2) === MASK1;
        }
    </script>
</body>

</html>